from fastapi import APIRouter, Request
from utils import create_json_response
import json

router = APIRouter()

@router.post("/contact/users")
async def get_contact_users(request: Request):
    """获取联系人列表 - 接收原始数据流并解析部门ID"""
    
    # 读取原始数据流
    body = await request.body()
    
    # 尝试解析数据流中的id参数
    try:
        # 如果是JSON格式
        data = json.loads(body.decode('utf-8'))
        dept_id = data.get('id', 0)
    except:
        # 如果是表单格式
        form_data = await request.form()
        dept_id = int(form_data.get('id', 0))
    
    # 部门数据映射
    departments = {
        1: {"id": 1, "name": "技术部", "dept": 1, "icon": "group-line"},
        2: {"id": 2, "name": "人事部", "dept": 2, "icon": "group-line"},
        3: {"id": 3, "name": "销售部", "dept": 3, "icon": "group-line"},
        4: {"id": 4, "name": "财务部", "dept": 4, "icon": "group-line"},
        11: {"id": 11, "name": "前端开发组", "dept": 11, "icon": "group-line"},
        12: {"id": 12, "name": "后端开发组", "dept": 12, "icon": "group-line"},
        13: {"id": 13, "name": "测试组", "dept": 13, "icon": "group-line"}
    }
    
    # 人员数据映射
    members = [
        {"id": 101, "name": "张三", "phone": "13800138001", "url": "https://******/avatar1.jpg"},
        {"id": 102, "name": "李四", "phone": "13800138002", "url": "https://******/avatar2.jpg"},
        {"id": 201, "name": "王人事", "phone": "13800138003", "url": "https://******/avatar3.jpg"},
        {"id": 202, "name": "赵招聘", "phone": "13800138004", "url": "https://******/avatar4.jpg"},
        {"id": 301, "name": "李销售", "phone": "13800138005", "url": "https://******/avatar5.jpg"},
        {"id": 302, "name": "周客户", "phone": "13800138006", "url": "https://******/avatar6.jpg"}
    ]
    
    # 根据解析的ID返回对应的数据
    if dept_id == 0:
        # 根目录：返回所有部门 + 所有人员
        contact_list = list(departments.values()) + members
    elif dept_id == 1:
        # 技术部：返回二级部门和成员
        contact_list = [
            departments[11],  # 前端开发组
            departments[12],  # 后端开发组
            departments[13],  # 测试组
            {"id": 101, "name": "张三", "phone": "13800138001", "url": "https://******/avatar1.jpg"},
            {"id": 102, "name": "李四", "phone": "13800138002", "url": "https://******/avatar2.jpg"}
        ]
    elif dept_id == 2:
        # 人事部：返回成员
        contact_list = [
            {"id": 201, "name": "王人事", "phone": "13800138003", "url": "https://******/avatar3.jpg"},
            {"id": 202, "name": "赵招聘", "phone": "13800138004", "url": "https://******/avatar4.jpg"}
        ]
    elif dept_id == 3:
        # 销售部：返回成员
        contact_list = [
            {"id": 301, "name": "李销售", "phone": "13800138005", "url": "https://******/avatar5.jpg"},
            {"id": 302, "name": "周客户", "phone": "13800138006", "url": "https://******/avatar6.jpg"}
        ]
    else:
        contact_list = []
    
    return create_json_response(contact_list)